// 存储颜色相关的转换
// 1. gyColor是格宇的颜色值，rgb数值的家和
// 2. rbg255str, 示例"rgb(0, 255, 3)"

// 将格宇的颜色值转为rgb范围(0, 255)的字符串
function gyColor2rgb255str(color: any) {
  if (typeof color == "number") {
    const blue = color & 0xff;
    const green = (color & 0xff00) >> 8;
    const red = (color & 0xff0000) >> 16;
    return "rgb(" + red + "," + green + ", " + blue + ")";
  }
  return color;
}

// 将格宇的颜色值转为rgb范围(0, 255)的数组
function gyColor2rgb255arr(color: number) {
  const blue = color & 0xff;
  const green = (color & 0xff00) >> 8;
  const red = (color & 0xff0000) >> 16;
  return [red, green, blue];
}

// 将rgb(25, 255, 1)字符串转为格宇的颜色数值
function rgb255str2gyColor(colorStr: string) {
  const rgb = colorStr.match(/\d+/g)?.map(Number) || [];
  if (rgb.length == 3) {
    return (rgb[0] << 16) + (rgb[1] << 8) + rgb[2];
  }
  return 0;
}

// 将rgb(0.2, 0.3, 1.0)数组转为格宇的颜色数值
function rgb1arr2gyColor(color: number[]) {
  return ((color[0] * 255) << 16) + ((color[1] * 255) << 8) + color[2] * 255;
}

function str_or_rgb1arr2gyColor(color: any) {
  if (typeof color == "string") {
    return rgb255str2gyColor(color);
  }
  if (color.length && color.length == 3 && color[0] <= 1.0) {
    return rgb1arr2gyColor(color);
  }
  if (typeof color == "number") return color;
  alert("failed to convert color");
  alert("color:" + color);
  return 1;
}

// 将格宇颜色值或者rgb1str转为转为rgb 255数组
function color2rgb255arr(color: any) {
  if (typeof color == "number") {
    return gyColor2rgb255arr(color);
  }
  if (typeof color == "string") {
    return rgb255str2arr(color);
  }

  console.error("color is not geyu number:", color);
  return [255, 0, 0]; // 默认值红色
}

// 将rgb 255字符串转为rgb范围(0, 1)的数组
function rgb255str2rgb1arr(colorStr: string) {
  const rgb = colorStr.match(/\d+/g)?.map(Number) || [];
  if (rgb.length == 3) {
    return [rgb[0] / 255.0, rgb[1] / 255.0, rgb[2] / 255.0];
  }
  return [0, 0, 0];
}

// 将rgb 255字符串转为rgb 255 数组
function rgb255str2arr(colorStr: string) {
  const rgb = colorStr.match(/\d+/g)?.map(Number) || [];
  if (rgb.length == 3) {
    return [rgb[0], rgb[1], rgb[2]];
  }
  return [0, 0, 0];
}

export {
  gyColor2rgb255str,
  rgb255str2gyColor,
  color2rgb255arr,
  rgb255str2rgb1arr,
  str_or_rgb1arr2gyColor,
};
